<?php

namespace tbollmeier\kakuromaster\core;

use tbollmeier\combinatorix\Selections;

class Sums
{
    public function __construct($values)
    {
        $this->values = $values;
        $this->sums = null;
    }
    
    public function getSummands($sum, $n)
    {
        if ($this->sums === null) {
            $this->initSums();
        }
        
        if (array_key_exists($sum, $this->sums)) {
            $nSums = $this->sums[$sum];
            if (array_key_exists($n, $nSums)) {
                return $nSums[$n];
            } else {
                return [];
            }
        } else {
            return [];
        }
    }
    
    public function getSummandsSet($sum, $n)
    {
        $set = new Set();
        $sums = $this->getSummands($sum, $n);
        
        foreach($sums as $summands) {
            $set->add($summands);
        }
       
        return $set;
    }
    
    private $values;
    private $sums;
    
    private function initSums()
    {
        $this->sums = [];
        $selections = Selections::create($this->values, 1, count($this->values));
        
        foreach ($selections as $selection) {
            $sum = array_sum($selection);
            $n = count($selection);
            if (!array_key_exists($sum, $this->sums)) {
                $this->sums[$sum] = [];
            }
            $nSums = &$this->sums[$sum];
            if (array_key_exists($n, $nSums)) {
                array_push($nSums[$n], $selection);
            } else {
                $nSums[$n] = [$selection];
            }
        }
        
    }    

}